/**
 * Created by 55456 on 2016/4/10.
 */
var db = require("../models/index");
var User = db.models.User;
var Story = db.models.Story;
var Follow = db.models.Follow;
var UserStory = db.models.UserStory;

var getUserInfo = function *(id,isOwn){
    var user = yield User.findOne({
        where: {
            id: id
        },
        attributes: { exclude: ["password"] }
    });
    return yield returnParsedUserData(user,isOwn);
};

var updateUserInfo = function *(id,data){
    yield User.update({
        userName:data.userName,
        sign:data.sign,
        sex:data.sex,
        avatar:data.avatar,
        noticeEnable:data.noticeEnable,
        followingEnable:data.followingEnable,
        followerEnable:data.followerEnable,
        aboutNotice:data.aboutNotice,
        updateNotice:data.updateNotice
    },{
        where:{
            id:id
        }
    });
    var user = yield User.findOne({
        where:{
            id:id
        },
        attributes: { exclude: ["password"] }
    });
    return yield returnParsedUserData(user,true);
};

var returnParsedUserData = function * (user,isOwn){
    var collectedStories = yield user.getStories({through:{
        where:{
            isCollection:1
        }
    }});
    var follower = yield user.getFollower({
        attributes: { exclude: ["password"] }
    });
    var following = yield user.getStar({
        attributes: { exclude: ["password"] }
    });

    follower = isOwn || user.followerEnable ? follower : ["false"];
    following = isOwn || user.followingEnable ? following : ["false"];

    followerCount = follower.length;
    followingCount  = following.length;
    collectedStoriesCount = collectedStories.length;
    return {
        user:user,
        follower:follower,
        following:following,
        collectedStoriesCount:collectedStoriesCount
    };
};

var addStar = function *(id,starID){
    try{
        var user = yield User.findOne({
            where:{
                id:id
            }
        });
        var star = yield User.findOne({
            where:{
                id:starID
            }
        });
        yield user.addStar(star);
        return {starID:star.id};
    }catch(err){
        console.log(err);
        return err;
    }
};

var delStar = function *(id,starID){
    try{
        var user = yield User.findOne({
            where:{
                id:id
            }
        });
        var star = yield User.findOne({
            where:{
                id:starID
            }
        });
        yield user.removeStar(star);
        return {action:true};
    }catch(err){
        console.log(err);
        return err;
    }
};

module.exports = {
    getUserInfo,
    updateUserInfo,
    addStar,
    delStar
};